package com.itheima.ai.controller;

import com.itheima.ai.service.IChatHistoryService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

/**
 * 对话控制器
 *
 * @Author mr.wu
 * @Date 2025-11-4 9:47
 */
@CrossOrigin
@RestController
@RequestMapping("/ai")
public class ChatController {

    @Autowired
    private ChatClient chatClient;


    /**
     * 简单文本对话接口-同步调用
     * @param prompt
     * @return
     */
    @GetMapping("/chat")
    public String chat(@RequestParam(defaultValue = "讲个笑话") String prompt) {
        return chatClient.prompt()
                .user(prompt)//用户提示词
                .call() //同步调用
                .content(); //获取响应
    }

    @Autowired
    private IChatHistoryService chatHistoryService;

    /**
     * 简单文本对话接口-流式输出
     * @param prompt
     * @return
     */
    @RequestMapping(value = "/stream", produces = "text/html;charset=utf-8")
    public Flux<String> stream(@RequestParam(defaultValue = "讲个笑话") String prompt, String chatId) {

        chatHistoryService.saveHistory("chat", chatId, null);

        return chatClient.prompt()
                .advisors(a->a.param(ChatMemory.CONVERSATION_ID, chatId)) //指定对话时的会话ID
                .user(prompt)//用户提示词
                .stream() //流式异步调用
                .content(); //获取响应
    }

//    /**
//     * 简单文本对话接口-SSE协议流式输出（企业级项目使用）
//     * @param prompt
//     * @return
//     */
//    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public Flux<String> stream(@RequestParam(defaultValue = "讲个笑话") String prompt) {
//        return chatClient.prompt()
//                .user(prompt)//用户提示词
//                .stream() //流式异步调用
//                .content(); //获取响应
//    }

    @Autowired
    public ChatClient chatServiceClient;



    /**
     * 黑马智能客服对话接口
     * @param prompt
     * @param chatId
     * @return
     */
    @RequestMapping("/service")
    public Flux<String> chatService(String prompt,String chatId) {
        chatHistoryService.saveHistory("service",chatId,null);

        return chatServiceClient.prompt()
                .user(prompt)
                .advisors(a->a.param(ChatMemory.CONVERSATION_ID,chatId))
                .stream()
                .content();
    }

    @Autowired
    private ChatClient chatPdfClient;


    /**
     * RAG知识库-ChatPDF对话接口
     * @param prompt
     * @param chatId
     * @return
     */
    @RequestMapping("/pdf/chat")
    public Flux<String> chatPDF(String prompt,String chatId) {
        chatHistoryService.saveHistory("pdf",chatId,null);

        return chatPdfClient.prompt()
                .user(prompt)
                .advisors(a->a.param(ChatMemory.CONVERSATION_ID,chatId))
                .stream()
                .content();
    }
}
